# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import requests
from itertools import product
from common.helper import Helper
from common.config import *
import json


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "海陆空交通意外险"

    # 生产数据
    def genProductInfo(self):

        plan = {
            "planCode": ["planA", "planB", "planC", "planD", "planE"],
            "days": ["1m", "3m", "6m", "1y"],
            "people_count": ["1"]
        }

        for v in product(plan["planCode"], plan["days"], plan["people_count"]):
            yield v

    # 执行爬虫
    def requestJson(self, data=None, true="true"):

        for v in self.genProductInfo():

            if v[0] == "planA":

                print("/*方案一")

                if "m" in v[1]:

                    days = "month_" + v[1].replace("m", "")

                else:

                    days = "term_1"

                result = {

                    "airplane_death": "1000000",
                    "train_death": "200000",
                    "ship_disability": "200000",
                    "passenger_death": "100000",
                }

                data = {"saleItemId": 10032, "quantity": 1, "policyPeriodNumber": "" + days + "",
                        "eachSumAssuredFlag": true,
                        "eachSumAssured": ["飞机:1000000", "轨道:200000", "轮船:200000", "公路:100000"],
                        "premPeriodNumber": "single"}

                payload = json.dumps(data)

                r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

                if r.status_code == 200:
                    price = (Helper.decimalParse(r.json()["data"]["totalPermium"]))

                    data = {
                        "name": self.name,
                        "company": "横琴人寿",
                        "days": v[1],
                        "people_count": "1",
                        "price": price
                    }

                    data.update(result)
                    self.mergeTable(data)



            elif v[0] == "planB":

                print("/*方案二")

                if "m" in v[1]:

                    days = "month_" + v[1].replace("m", "")

                else:

                    days = "term_1"

                result = {

                    "airplane_death": "1000000",
                    "train_death": "200000",
                    "ship_disability": "200000",
                    "passenger_death": "100000",
                }

                data = {"saleItemId": 10032, "quantity": 2, "policyPeriodNumber": "" + days + "",
                        "eachSumAssuredFlag": true,
                        "eachSumAssured": ["飞机:2000000", "轨道:400000", "轮船:400000", "公路:200000"],
                        "premPeriodNumber": "single"}

                payload = json.dumps(data)

                r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

                if r.status_code == 200:
                    price = (Helper.decimalParse(r.json()["data"]["totalPermium"]))

                    data = {
                        "name": self.name,
                        "company": "横琴人寿",
                        "days": v[1],
                        "people_count": "1",
                        "price": price
                    }

                    data.update(result)
                    self.mergeTable(data)



            elif v[0] == "planC":

                print("/*方案三")

                if "m" in v[1]:

                    days = "month_" + v[1].replace("m", "")

                else:

                    days = "term_1"

                result = {

                    "airplane_death": "1000000",
                    "train_death": "200000",
                    "ship_disability": "200000",
                    "passenger_death": "100000",
                }

                data = {"saleItemId": 10032, "quantity": 3, "policyPeriodNumber": "" + days + "",
                        "eachSumAssuredFlag": true,
                        "eachSumAssured": ["飞机:3000000", "轨道:600000", "轮船:600000", "公路:300000"],
                        "premPeriodNumber": "single"}

                payload = json.dumps(data)

                r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

                if r.status_code == 200:
                    price = (Helper.decimalParse(r.json()["data"]["totalPermium"]))

                    data = {
                        "name": self.name,
                        "company": "横琴人寿",
                        "days": v[1],
                        "people_count": "1",
                        "price": price
                    }

                    data.update(result)
                    self.mergeTable(data)



            elif v[0] == "planD":
                print("/*方案四")

                if "m" in v[1]:

                    days = "month_" + v[1].replace("m", "")

                else:

                    days = "term_1"

                result = {

                    "airplane_death": "1000000",
                    "train_death": "200000",
                    "ship_disability": "200000",
                    "passenger_death": "100000",
                }

                data = {"saleItemId": 10032, "quantity": 4, "policyPeriodNumber": "" + days + "",
                        "eachSumAssuredFlag": true,
                        "eachSumAssured": ["飞机:4000000", "轨道:800000", "轮船:800000", "公路:400000"],
                        "premPeriodNumber": "single"}

                payload = json.dumps(data)

                r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

                if r.status_code == 200:
                    price = (Helper.decimalParse(r.json()["data"]["totalPermium"]))

                    data = {
                        "name": self.name,
                        "company": "横琴人寿",
                        "days": v[1],
                        "people_count": "1",
                        "price": price
                    }

                    data.update(result)
                    self.mergeTable(data)



            else:
                print("/*方案五")

                if "m" in v[1]:

                    days = "month_" + v[1].replace("m", "")

                else:

                    days = "term_1"

                result = {

                    "airplane_death": "1000000",
                    "train_death": "200000",
                    "ship_disability": "200000",
                    "passenger_death": "100000",
                }

                data = {"saleItemId": 10032, "quantity": 5, "policyPeriodNumber": "" + days + "",
                        "eachSumAssuredFlag": true,
                        "eachSumAssured": ["飞机:5000000", "轨道:1000000", "轮船:1000000", "公路:500000"],
                        "premPeriodNumber": "single"}

                payload = json.dumps(data)

                r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

                if r.status_code == 200:
                    price = (Helper.decimalParse(r.json()["data"]["totalPermium"]))

                    data = {
                        "name": self.name,
                        "company": "横琴人寿",
                        "days": v[1],
                        "people_count": "1",
                        "price": price
                    }

                    data.update(result)
                    self.mergeTable(data)

    # 合并表格
    def mergeTable(self, data):

        SQL = 'INSERT INTO `' + TABLE_ACCIDENT + '`(`name`,`company`,`days`,`people_count`,`price`,`airplane_death`,`train_death`,`ship_disability`,`passenger_death`)VALUES("{name}","{company}","{days}","{people_count}","{price}","{airplane_death}","{train_death}","{ship_disability}","{passenger_death}")'

        print(SQL.format(**data))

        self.mysql.cursor.execute(SQL.format(**data))
        self.mysql._conn.commit()
